package 
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.utils.getTimer;
	
	/**
	 * ...
	 * @author Joseph Waters
	 */
	[SWF(backgroundColor="0x000000" , width="650" , height="480")] // Set stage color and size
	public class Main extends Sprite 
	{
		public var keysDown:Array = new Array(); // Create an array of all keys pressed for easy tracking
		private var lastTime:Number = getTimer();
		private var gameGraphics:GameGraphics;
		private var gameLogic:Logic;
		
		private var planetMenuOpen:Boolean = false;
		
		public function Main():void
		{
			if (stage) {
				init();
			}
			else {
				addEventListener(Event.ADDED_TO_STAGE, init);
			}
		}
		
		private function init(e:Event = null):void 
		{			
			removeEventListener(Event.ADDED_TO_STAGE, init);
			
			// Initialize local variables and event listeners
			keysDown.push(-1); // Add 0 index item to keys array to prevent indexing errors or null array
			gameGraphics = new GameGraphics(this);
			gameLogic = new Logic();
			
			stage.addEventListener(MouseEvent.MOUSE_MOVE, moveMouse, false, 0, true); // Mouse movement tracking
			stage.addEventListener(MouseEvent.MOUSE_UP, upMouse, false, 0, true); // Mouse click release
			stage.addEventListener(KeyboardEvent.KEY_DOWN, downKey, false, 0, true); // Keys down
			stage.addEventListener(KeyboardEvent.KEY_UP, upKey, false, 0, true); // Keys up
			
			// Init game graphics
			
			gameGraphics.init();
			
			// Start game logic
			gameLogic.init();
			
			stage.addEventListener(Event.ENTER_FRAME, gameLoop, false, 0, true); // Start game loop
		}
		
		// Game Loop
		private function gameLoop(event:Event):void {
			gameLogic.step(keysDown);
			gameGraphics.update();
			lastTime = getTimer();
		}
		
		// Pass mouse movement to the gameLogic
		private function moveMouse(event:MouseEvent):void {
			gameLogic.checkMouseMove(event);
		}
		
		// Pass upMouse event to gameLogic
		private function upMouse(event:MouseEvent):void {
			gameLogic.checkMouseUp(event);
		}
		
		// Add keys pressed to the keysDown array
		private function downKey(event:KeyboardEvent):void {
			if (keysDown.indexOf(event.keyCode) < 0) {
				keysDown.push(event.keyCode);
			}
		}
		
		// Remove keys pressed from the keysDown array
		private function upKey(event:KeyboardEvent):void {
			if (keysDown.indexOf(event.keyCode) > 0) {
				keysDown.splice(keysDown.indexOf(event.keyCode)); // Remove the key from the array
			}
		}
		
		// Function to track planet menu open and close
		public function menuSwitch():Boolean {
			if (planetMenuOpen) { planetMenuOpen = false; }
			else { planetMenuOpen = true; }
			
			return planetMenuOpen;
		}
	}
	
}